#include "recbox.h"
#include "ui_recbox.h"
#include "rectboxitem.h"
#include <QJsonObject>
#include <QList>
#include <QDebug>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox)
{
    ui->setupUi(this);


}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray objArray, int rows)
{
   this->imageList = objArray;
   this->count = imageList.size() / col;
   this->counts = imageList.size() / (2 * col);

//    qDebug() << count;
//    qDebug() << counts;

   if (rows == 1)
   {
       ui->recListDown->hide();
       createRecBoxItem();

   }
   else
   {
       this->row = 2;
       createRecBoxItems();

   }
}

void RecBox::createRecBoxItem()
{
    for (int i = this->currentIndex * col; i <this->currentIndex * col + col; i++)
    {
        RectBoxItem* item = new RectBoxItem();

        QJsonObject obj = imageList[i].toObject();
        QString text = obj.value("text").toString();
        QString image = obj.value("path").toString();
        item->setRecText(text);
        item->setRecImage(image);

        ui->recListUpHLayout->addWidget(item);
    }
}

void RecBox::createRecBoxItems()
{
    for (int i = this->currentIndex * col * 2; i <this->currentIndex * col * 2 +  col * 2; i++)
    {
        RectBoxItem* item = new RectBoxItem();

        QJsonObject obj = imageList[i].toObject();
        QString text = obj.value("text").toString();
        QString image = obj.value("path").toString();
        item->setRecText(text);
        item->setRecImage(image);

        if (i < this->currentIndex * col * 2 + col)
        {
            ui->recListUpHLayout->addWidget(item);
        }
        else
        {
            ui->recListDownHLayout->addWidget(item);
        }
    }
}

void RecBox::clearRecImageUp()
{
    QList<RectBoxItem*> items = ui->recListUp->findChildren<RectBoxItem*>();

    for (auto child : items)
    {
        ui->recListUpHLayout->removeWidget(child);
        delete child;
    }
}

void RecBox::clearRecImageDown()
{
    QList<RectBoxItem*> items = ui->recListDown->findChildren<RectBoxItem*>();

    for (auto child : items)
    {
        ui->recListDownHLayout->removeWidget(child);
        delete child;
    }
}


void RecBox::on_BtUp_clicked()
{
    clearRecImageUp();
    clearRecImageDown();

    currentIndex--;

    if (this->row == 1)
    {
        if (currentIndex < 0)
        {
            currentIndex = count - 1;
        }

        createRecBoxItem();
    }
    else
    {
        if (currentIndex < 0)
        {
            currentIndex = counts - 1;

//            qDebug() << count;
//            qDebug() << counts;
        }

        createRecBoxItems();
    }
}

void RecBox::on_btDown_clicked()
{
    clearRecImageUp();
    clearRecImageDown();

    this->currentIndex++;


    if (this->row == 1)
    {
        currentIndex %= count;
        createRecBoxItem();
    }
    else
    {
        currentIndex %= counts;
        createRecBoxItems();
    }

}
